// pages/contact/contact.js
const app = getApp();
// 输入值
var inputVal = '';
var msgList = [];
var windowWidth = wx.getSystemInfoSync().windowWidth;
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;

/**
 * 初始化数据
 */
function initData(that) {
  inputVal = '';

  msgList = [
  //   {
  //   speaker: 'server', //客服
  //   contentType: 'text',
  //   content: '欢迎来到英雄联盟，敌军还有30秒到达战场，请做好准备！'
  // },
  // {
  //   speaker: 'customer',  // 客户
  //   contentType: 'text',
  //   content: '我怕是走错片场了...'
  // }
  ]
  that.setData({
    msgList,
    inputVal
  })
}

/**
 * 计算msg总高度
 */
// function calScrollHeight(that, keyHeight) {
//   var query = wx.createSelectorQuery();
//   query.select('.scrollMsg').boundingClientRect(function(rect) {
//   }).exec();
// }

Page({

  /**
   * 页面的初始数据
   * vw和vh是css3中的中的新单位，是一种视窗单位，小程序中也同样适用

      小程序中，窗口固定宽度为100vw，将窗口宽度平均分为100份，每一份是1vw。
      小程序中，窗口固定高度为100vh，将窗口高度平均分为100份，每一份是1vh。
   */
  data: {
    content: '',  // client要发送的内容
    scrollHeight: '100vh',
    inputBottom: 0,
    // 客服ID
    customer_ID: '',
    myID: '',// 自己的ID
    // 客服头像地址
    customer_headImage: 'https://636c-cloud1-1gdy9qn04afa7135-1306431321.tcb.qcloud.la/customer_service.png?sign=c5850e7d3b72fd97a1280086c6946bea&t=1636602865',
    // 本人头像地址
    my_headImage:'',
    onlineTime:'', // 在线时间
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    initData(that);
    // 和服务器建立连接
    that.createWebsocketConnect()
    // this.setData({
    //   cusHeadIcon: app.globalData.userInfo.avatarUrl,
    // });
  },


  /**
   *      获取聚焦  即底部input表单获取焦点时
   */
  focus: function (e) {

    /*
          输入框聚焦时触发，event.detail = { value, height }，height 为键盘高度，
    */
    keyHeight = e.detail.height;
    console.log("键盘高度=" + keyHeight)
    this.setData({
      scrollHeight: (windowHeight - keyHeight) + 'px'
    });
    this.setData({
      toView: 'msg-' + (msgList.length - 1),
      // inputBottom:代表底部键盘弹起时input的高度
      inputBottom: keyHeight + 'px'
    })
    //计算msg高度
    // calScrollHeight(this, keyHeight);

  },

  //失去聚焦(软键盘消失)
  blur: function (e) {
    this.setData({
      scrollHeight: '100vh',
      inputBottom: 0
    })
    this.setData({
      toView: 'msg-' + (msgList.length - 1)
    })

  },

  /**
   * 发送点击监听
   */
  sendClick: function (e) {
    var that = this
    that.setData({
      content: e.detail.value
    })
    msgList.push({
      speaker: 'customer',
      contentType: 'text',
      content: e.detail.value
    })
    inputVal = '';
    this.setData({
      msgList,
      inputVal
    });
    // 给服务器发消息
    that.getsendSocketMessage()


  },

  /**
   * 退回上一页
   */
  toBackClick: function () {
    wx.navigateBack({})
  },
  // websocket会话连接

  // 创建一个websocket连接
  createWebsocketConnect() {
    var that = this
    wx.connectSocket({
      url: 'ws://localhost:8081/server',
      method: 'GET',
      header: {
        'content-type': 'application/json',
      },
      protocols: ['ws'],
      timeout: 10000,
      success(res) {
        console.log('连接创建成功！！')
      },
      fail(err) {
        console.log('连接创建失败！！')
      }
    })
    this.getSocketOpen()
    // this.getsendSocketMessage()
    this.getonSocketMessage()
    // this.getonSocketError()
    this.getonSocketClose()
  },

  // 监听连接事件
  getSocketOpen() {
    wx.onSocketOpen(res => {
      console.log('连接建立成功！')
      console.log(res)
    })
  },
  // 给服务器发消息
  getsendSocketMessage() {
    var that = this
    wx.sendSocketMessage({
      data: JSON.stringify(that.messageBody()),
      success(res) {
        console.log('消息发送成功！！')
      },
      fail(err) {
        console.log('消息发送失败！！')
      }
    })
  },
  // 监听 WebSocket 接受到服务器的消息事件
  getonSocketMessage() {
    var that = this
    wx.onSocketMessage((result) => {
      console.log('服务器发消息过来了')
      // 将json对象转为js对象
      var Data = JSON.parse(result.data)
      console.log('下面为服务器发过来的数据:')
      console.log(Data)
      // 获取客服的ID
      if (that.data.customer_ID == '' || that.data.myID == '') {
        that.setData({
          customer_ID: Data.content.map.customer_serviceID,
          myID: Data.accept_people_ID,
          onlineTime:Data.send_time,
          my_headImage:Data.content.map.accpeter.head_img,
        })
      }
      // 将获取的消息push到msgList列表中 让页面展示
      if (Data.content.map.message!=null && Data.content.map.message!=undefined) {
        msgList.push({
          speaker: 'server', // 客服
          contentType: 'text',
          content: Data.content.map.message
        })
        console.log("msgList内容如下：" + msgList)
        // 加上这一句才能显示服务器发过来的消息
        this.setData({
          msgList,
        });
      }
    })
  },

  // 监听 WebSocket 错误事件
  getonSocketError() {
    wx.onSocketError((result) => {
      console.log('连接出错！！')
    })
  },
  // 监听 WebSocket 连接关闭事件
  getonSocketClose() {
    wx.onSocketClose((result) => {
      console.log('连接关闭了')
    })
  },
  // 发送给客服消息的一个消息体
  messageBody() {
    var that = this
    var parms={}
    parms=that.getLocalUserMessage()  //接收用户的基本信息

    var sex=parms.sex
    var area=parms.area
    var signature=parms.signature
    var role=parms.role
    var username=parms.username


    var sendMessageBody = {
      sender_ID: that.data.myID,
      sender_name: username,
      content: {
        type: 'text',
        map: {
          message: that.data.content,
          customer_serviceID: that.data.customer_ID,
          file: null,
          binary: null,
          allClient: null,
          // 发送者基本信息
          sender:{
            ID:that.data.myID,
            username:username,
            sex:sex,
            area:area,
            signature:signature,
            role:role,
            onlinStatus:'在线',
            onlineTime:that.data.onlineTime,
            offlineTime:null,
            head_img:that.data.my_headImage,
        },
        // 接受者基本信息
        accpeter:{
          ID:that.data.customer_ID,
          username:'客服1号',
          sex:'女生',
          area:'上海',
          signature:'为用户服务',
          role:'admin',
          onlineTime:null,
          offlineTime:null,
          head_img:null,
      }

        }
      },
      accept_people_ID: that.data.customer_ID,  //接收人的ID
      accept_people_Name: '客服1号', // 接收人的名字
      send_time: that.getSubmitTime()
    }
    return sendMessageBody
  },
  // 获取发送的时间
  getSubmitTime() {
    var nowTime = ""
    var time = new Date()
    var year = time.getFullYear()
    var month = time.getMonth() + 1
    var day = time.getDate()
    var hour = time.getHours()
    var minute = time.getMinutes()
    var seconds = time.getSeconds()
    nowTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + seconds
    console.log("现在的时间是:" + nowTime)
    return nowTime
  },
  // 获取用户本地存储的用户的基本信息
  getLocalUserMessage(){
    var parms={}
    var sex=wx.getStorageSync('basicMessage').sex
    var area=wx.getStorageSync('basicMessage').area
    var signature=wx.getStorageSync('basicMessage').signature
    var role=wx.getStorageSync('basicMessage').role
    var username = wx.getStorageSync('userMessage').user

    parms.sex=sex
    parms.area=area
    parms.signature=signature
    parms.role=role
    parms.username=username

    return parms
  }

})
